﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class EventManager
{
    public static Dictionary<string, Action> zeroInEventDict;

    #region 无参
    /// <summary>
    /// 添加监听
    /// </summary>
    /// <param name="eventName"></param>
    /// <param name="action"></param>
    public static void AddListener(string eventName,Action action)
    {
        if(zeroInEventDict == null)
        {
            zeroInEventDict = new Dictionary<string, Action>();
        }
        if(zeroInEventDict.ContainsKey(eventName))
        {
            zeroInEventDict[eventName] += action;
        }
        else
        {
            zeroInEventDict.Add(eventName, new Action(action));
        }
    }
    /// <summary>
    /// 处理事件
    /// </summary>
    /// <param name="eventName"></param>
    /// <returns></returns>
    public static bool Dispatch(string eventName)
    {
        if (zeroInEventDict == null)
        {
            zeroInEventDict = new Dictionary<string, Action>();
        }
        if (zeroInEventDict.ContainsKey(eventName))
        {
            zeroInEventDict[eventName]?.Invoke();
            return true;
        }
        else
        {
            Debug.Log($"未注册 {eventName} 事件");
            return false;
        }
    }
    /// <summary>
    /// 移除所有事件的指定监听
    /// </summary>
    /// <param name="action"></param>
    public static void RemoveListener(Action action)
    {
        if (zeroInEventDict == null)
        {
            zeroInEventDict = new Dictionary<string, Action>();
        }
        foreach (string eventName in zeroInEventDict.Keys)
        {
            zeroInEventDict[eventName] -= action;
        }
    }
    /// <summary>
    /// 移除监听
    /// </summary>
    /// <param name="eventName"></param>
    /// <param name="action"></param>
    public static void RemoveListener(string eventName,Action action)
    {
        if (zeroInEventDict == null)
        {
            zeroInEventDict = new Dictionary<string, Action>();
        }
        if (zeroInEventDict.ContainsKey(eventName))
        {
            zeroInEventDict[eventName] -= action;
        }
    }
    /// <summary>
    /// 移除事件
    /// </summary>
    /// <param name="eventName"></param>
    public static void RemoveAllListener(string eventName)
    {
        if (zeroInEventDict == null)
        {
            zeroInEventDict = new Dictionary<string, Action>();
        }
        if (zeroInEventDict.ContainsKey(eventName))
        {
            zeroInEventDict[eventName] = null;
            zeroInEventDict.Remove(eventName);
        }
    }
    #endregion
}
